package com.wzl.jdbc.config;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 复合分表算法
 *
 * @author weizhongli
 * @since 1.0, 2024/05/14 14:47
 */
public class MyTableComplexKeysShardingAlgorithm implements ComplexKeysShardingAlgorithm<Integer> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<Integer> complexKeysShardingValue) {
        //需求上我们是根据id范围查询，根据number精确查询 所以
        // id用getColumnNameAndRangeValuesMap
        // number用getColumnNameAndShardingValuesMap
        Range<Integer> idRange = complexKeysShardingValue.getColumnNameAndRangeValuesMap().get("id");
        Collection<Integer> typeCol = complexKeysShardingValue.getColumnNameAndShardingValuesMap().get("number");

        List<String> res = new ArrayList<>();

        for (Integer number : typeCol) {
            BigInteger bigInteger = BigInteger.valueOf(number);
            BigInteger target = bigInteger.mod(new BigInteger("2"));
            res.add(complexKeysShardingValue.getLogicTableName() + "_" + target);
        }
        return res;

    }
}
